import base64
import json
import os
import sys
import smtplib
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import yagmail

import xlsxwriter

from config import content, var_idx, choice
from config import path

import importlib
importlib.reload(sys)

# dict转json文件
def dict_to_json_write_file(filename, config_dict):  # 输出json
    with open(filename, 'w', encoding='utf-8') as f:
        json.dump(config_dict, f, ensure_ascii=False)


# json转dict
def json_file_to_dict(filename):  # 读json
    with open(filename, 'r', encoding='utf-8') as f:
        dictgroup = json.load(fp=f)
    return dictgroup


# 图片decode
def pic_decode(pic_content, pic_path, pic_name):
    img_data = base64.b64decode(pic_content)
    img_file = open("{0}/{1}.png".format(pic_path, pic_name), 'wb')
    img_file.write(img_data)
    img_file.close()


# 生成excel
def excel_writer(path, excel_name, params):
    workbook = xlsxwriter.Workbook(path + '/' + excel_name)
    worksheet = workbook.add_worksheet("详细信息")
    format_title = workbook.add_format({'text_wrap': 1, 'bold': True, 'align': 'left', 'valign': 'vcenter'})
    format_content = workbook.add_format({'text_wrap': 1, 'bold': False, 'align': 'center', 'valign': 'vcenter'})
    format_grey = workbook.add_format({'bg_color': '#7F7F7F'})
    worksheet.write_string(0, 0, "光伏电站综合信息收集表", format_title)
    # 第一列输入
    for inx, item in var_idx[0]:
        worksheet.write(inx, 0, content[item], format_title)
        worksheet.write(inx, 1, params[item], format_content)
    # 第一列bool类型
    for inx, item in var_idx[1]:
        worksheet.write(inx, 0, content[item], format_title)
        worksheet.write(inx, 1, choice[item][int(params[item])], format_content)
    # 全局条件判断输入
    for inx1, inx2, item in var_idx[2]:
        worksheet.write(inx1, inx2, content[item], format_title)
    if params['descrip_gridC'] > 0:
        worksheet.write(10, 1, params['time_first_gridC'], format_content)
    else:
        worksheet.write(10, 1, '', format_grey)

    if params['descrip_gridC'] > 2:
        worksheet.write(11, 1, params['time_all_gridC'], format_content)
    else:
        worksheet.write(11, 1, '', format_grey)

    if params['descrip_gridC'] == 3:
        for inx1, inx2, item in var_idx[2]:
            worksheet.write(inx1, inx2 + 1, params[item], format_content)
    else:
        for inx1, inx2, item in var_idx[2]:
            worksheet.write(inx1, inx2 + 1, '', format_grey)
    if params['position_meter'] == 1:
        worksheet.write(14, 2, params['length_outline'], format_content)
    else:
        worksheet.write(14, 2, '', format_grey)
    if params['condition_1'] == 1:
        worksheet.write(62, 3, params['cost_condition_1'], format_content)
    else:
        worksheet.write(62, 3, '', format_grey)
    if params['condition_2'] == 1:
        worksheet.write(63, 3, params['cost_condition_2'], format_content)
    else:
        worksheet.write(63, 3, '', format_grey)
    if params['condition_3'] == 1:
        worksheet.write(64, 3, params['cost_condition_3'], format_content)
    else:
        worksheet.write(64, 3, '', format_grey)
    if params['condition_4'] == 1:
        worksheet.write(65, 3, params['cost_condition_4'], format_content)
    else:
        worksheet.write(65, 3, '', format_grey)
    # 人员配置、交通、清洗除草
    worksheet.write(45, 2, '人数', format_title)
    worksheet.write(53, 2, '型号', format_title)
    worksheet.write(53, 3, '数量', format_title)
    worksheet.write(54, 1, '汽车', format_title)
    worksheet.write(55, 1, '三轮车', format_title)
    worksheet.write(56, 1, '船只', format_title)
    worksheet.write(59, 1, '电站清洗', format_title)
    worksheet.write(60, 1, '电站除草', format_title)
    worksheet.write(61, 1, '电站除雪', format_title)
    worksheet.write(58, 2, '次数（次/年）', format_title)
    worksheet.write(58, 3, '费用（元/MW）', format_title)
    for inx, item in var_idx[3]:  # 人员配置
        worksheet.write(inx, 1, content[item], format_title)
        worksheet.write(inx, 2, params[item], format_content)
    for inx1, inx2, item in var_idx[4]:  # 交通、清洗除草
        worksheet.write(inx1, inx2, params[item], format_content)

    col_inx = 1
    for ite in range(len(params['module'])):
        for inx, item in var_idx[5]:
            worksheet.write(inx, col_inx, content[item], format_title)
            if inx in [20, 23, 24, 27, 28, 36, 37, 38, 39]:
                worksheet.write(inx, col_inx + 1, choice[item][int(params['module'][ite][item])], format_content)
            else:
                worksheet.write(inx, col_inx + 1, params['module'][ite][item], format_content)
        row_inx = 29
        for item in var_idx[6][params['module'][ite]['type_rack']]:
            worksheet.write(row_inx, col_inx, content[item], format_title)
            worksheet.write(row_inx, col_inx + 1, params['module'][ite][item], format_content)
            row_inx += 1
        col_inx += 2

    worksheet.set_column(0, 0, 40)
    worksheet.set_column(1, 3, 35)
    if len(params['module']) > 1:
        worksheet.set_column(4, 3 + (len(params['module']) - 1) * 2 - 1, 35)
    worksheet.write('A15', '外线信息', format_title)
    worksheet.write('A16', '运维信息', format_title)
    worksheet.write('A17', '主变信息', format_title)
    worksheet.merge_range('A4:A5', '经纬度信息', format_title)
    worksheet.merge_range('A7:A8', '电站容量', format_title)
    worksheet.merge_range('A19:A40', '箱变信息（箱变、逆变器、组串、组件）', format_title)
    worksheet.merge_range('A46:A53', '人员配置', format_title)
    worksheet.merge_range('A54:A57', '交通工具配置', format_title)
    worksheet.merge_range('A59:A62', '清洗除草除雪', format_title)

    worksheet = workbook.add_worksheet(content["station_pics"])
    for num in range(len(params["station_pics"])):
        worksheet.insert_image(0, num * 8, path + '/station_' + str(num) + '.png', {'x_scale': 0.1, 'y_scale': 0.1})

    worksheet = workbook.add_worksheet(content["transp_pics"])
    for num in range(len(params["transp_pics"])):
        worksheet.insert_image(0, num * 8, path + '/trans_' + str(num) + '.png', {'x_scale': 0.1, 'y_scale': 0.1})

    workbook.close()


def sendEmail(input_params):
    obj_path = "{0}/{1}/{2}".format(path, '/'.join(input_params['area class']), input_params['station_no'])
    # noinspection PyBroadException
    orig_up = [name for name in os.listdir(obj_path) if
                 os.path.isdir(os.path.join(obj_path, name))]  # 最新版本
    latest_up = sorted(orig_up, key=lambda x:int(x[:-1]))[-1]
    file_path = "{0}/{1}".format(obj_path, latest_up)
    file_name = [name for name in os.listdir(file_path) if name.split('.')[-1] == 'xlsx'][-1]
    receivers = [input_params['email']]
    # send the email
    message = MIMEMultipart()
    message['From'] = Header("电站信息采集小程序", 'gbk')
    message['Subject'] = Header('电站收集信息', 'gbk')
    send_content = '{0}{1}{2}'.format('亲爱的电站信息采集小程序用户：\n\n',
                                      '         您好，您在小程序系统成功获取了电站信息文档，文档在附件中，请查收。\n\n',
                                      '感谢您对阳关电源的支持！')
    send_content=bytes(send_content, 'gbk')
    message.attach(MIMEText(send_content, 'plain', 'gbk'))  # 邮件正文内容
    attachment = MIMEText(open(os.path.join(file_path, file_name), 'rb').read(), 'base64', 'gbk')
    attachment.add_header('Content-Disposition', 'attachment', filename=('gbk', '', file_name))  # 附件1
    message.attach(attachment)
    # encoders.encode_base64(message)
    # send right away
    """发送邮件"""
    send_user = os.environ.get('MAIL_USERNAME')
    send_pwd = os.environ.get('MAIL_PASSWORD')
    smtp_server = os.getenv('MAIL_SERVER')
    smtp_port = 25
    server = smtplib.SMTP(smtp_server, smtp_port)
    server.login(send_user, send_pwd)
    server.sendmail(send_user, receivers, message.as_string())
    server.quit()
